<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @cancel="handleClose"
    @close="handleClose"
    size="80%"
  >
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <FormInfo>
        <template #left>订单信息</template>
        <template #content>
          <t-space direction="vertical" style="width: 100%" size="large">
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="订单名称" name="orderName">
                  <InputSelect
                    v-if="!pageData.readOnly"
                    :value="pageData.formData.orderName"
                    @onClick="handleOrderShow"
                  />
                  <div v-else class="form__text">{{ pageData.formData.orderName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="合同编号" name="contractNo" help="选择订单后自动带出">
                  <div class="form__text">{{ pageData.formData.contractNo }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-space>
        </template>
      </FormInfo>
      <FormInfo>
        <template #left>录入明细</template>
        <template #content>
          <t-space direction="vertical" style="width: 100%" size="large">
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="起运港" name="startPort">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.startPort"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.startPort }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="目的港" name="targetPort">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.targetPort"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.targetPort }}</div>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="中转港" name="transferPort">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.transferPort"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.transferPort }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="船公司" name="shipCompany">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.shipCompany"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.shipCompany }}</div>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="提单号" name="billNo">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.billNo"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.billNo }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="开船时间" name="startExpressTime">
                  <t-date-picker
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.startExpressTime"
                    enableTimePicker
                    style="width: 100%"
                    :format="datePickerFormat"
                  />
                  <div v-else class="form__text">
                    {{ dayjs(pageData.formData.startExpressTime).format("YYYY-MM-DD HH:mm") }}
                  </div>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="截单时间" name="cutoffTime">
                  <t-date-picker
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.cutoffTime"
                    enableTimePicker
                    style="width: 100%"
                    :format="datePickerFormat"
                  />
                  <div v-else class="form__text">
                    {{ dayjs(pageData.formData.cutoffTime).format("YYYY-MM-DD HH:mm") }}
                  </div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="截关时间" name="cutoffCustomsTime">
                  <t-date-picker
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.cutoffCustomsTime"
                    enableTimePicker
                    style="width: 100%"
                    :format="datePickerFormat"
                  />
                  <div v-else class="form__text">
                    {{ dayjs(pageData.formData.cutoffCustomsTime).format("YYYY-MM-DD HH:mm") }}
                  </div>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="到港时间" name="arriveTime">
                  <t-date-picker
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.arriveTime"
                    enableTimePicker
                    style="width: 100%"
                    :format="datePickerFormat"
                  />
                  <div v-else class="form__text">
                    {{ dayjs(pageData.formData.arriveTime).format("YYYY-MM-DD HH:mm") }}
                  </div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="运输方式" name="typeOfShipping">
                  <t-input
                    :showLimitNumber="true"
                    v-if="!pageData.readOnly"
                    v-model="pageData.formData.typeOfShipping"
                    maxlength="100"
                  />
                  <div v-else class="form__text">{{ pageData.formData.typeOfShipping }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-space>
        </template>
      </FormInfo>
      <FormInfo>
        <template #left>费用明细</template>
        <template #content>
          <t-space direction="vertical" style="width: 100%" size="large">
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="海运费" name="shippingCost">
                  <t-row v-if="!pageData.readOnly" style="width: 100%">
                    <t-col :span="4">
                      <t-select style="width: 100%" v-model="pageData.formData.shippingCostUnit">
                        <t-option
                          :value="item.value"
                          :label="item.label"
                          v-for="item in CURRENCY_LIST"
                          :key="item.value"
                        />
                      </t-select>
                    </t-col>
                    <t-col :span="7" :offset="1">
                      <t-input-number
                        :min="0"
                        style="width: 100%"
                        :decimalPlaces="2"
                        theme="column"
                        v-model="pageData.formData.shippingCost"
                      />
                    </t-col>
                  </t-row>
                  <div v-else class="form__text">{{ newPrecision(pageData.formData.shippingCost, 2) }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="港杂费" name="portMiscellaneousFees">
                  <t-row v-if="!pageData.readOnly" style="width: 100%">
                    <t-col :span="4">
                      <t-select style="width: 100%" v-model="pageData.formData.portMiscellaneousFeesUnit">
                        <t-option
                          :value="item.value"
                          :label="item.label"
                          v-for="item in CURRENCY_LIST"
                          :key="item.value"
                        />
                      </t-select>
                    </t-col>
                    <t-col :span="7" :offset="1">
                      <t-input-number
                        :min="0"
                        style="width: 100%"
                        :decimalPlaces="2"
                        theme="column"
                        v-model="pageData.formData.portMiscellaneousFees"
                      />
                    </t-col>
                  </t-row>
                  <div v-else class="form__text">{{ newPrecision(pageData.formData.portMiscellaneousFees, 2) }}</div>
                </t-form-item>
              </t-col>
            </t-row>
            <t-row>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="尾端派送费" name="tailDeliveryFees">
                  <t-row v-if="!pageData.readOnly" style="width: 100%">
                    <t-col :span="4">
                      <t-select style="width: 100%" v-model="pageData.formData.tailDeliveryFeesUnit">
                        <t-option
                          :value="item.value"
                          :label="item.label"
                          v-for="item in CURRENCY_LIST"
                          :key="item.value"
                        />
                      </t-select>
                    </t-col>
                    <t-col :span="7" :offset="1">
                      <t-input-number
                        :min="0"
                        style="width: 100%"
                        :decimalPlaces="2"
                        theme="column"
                        v-model="pageData.formData.tailDeliveryFees"
                      />
                    </t-col>
                  </t-row>
                  <div v-else class="form__text">{{ newPrecision(pageData.formData.tailDeliveryFees, 2) }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item :labelWidth="100" label="税金" name="tax">
                  <t-row v-if="!pageData.readOnly" style="width: 100%">
                    <t-col :span="4">
                      <t-select style="width: 100%" v-model="pageData.formData.taxUnit">
                        <t-option
                          :value="item.value"
                          :label="item.label"
                          v-for="item in CURRENCY_LIST"
                          :key="item.value"
                        />
                      </t-select>
                    </t-col>
                    <t-col :span="7" :offset="1">
                      <t-input-number
                        :min="0"
                        style="width: 100%"
                        :decimalPlaces="2"
                        theme="column"
                        v-model="pageData.formData.tax"
                      />
                    </t-col>
                  </t-row>
                  <div v-else class="form__text">{{ newPrecision(pageData.formData.tax, 2) }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-space>
        </template>
      </FormInfo>
      <FormInfo>
        <template #left>其他信息</template>
        <template #content>
          <t-row>
            <t-col :span="12">
              <t-form-item label="备注" name="remark" :labelWidth="100">
                <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" :autosize="{ minRows: 3 }" />
                <div v-else class="form__text">{{ pageData.formData.remark }}</div>
              </t-form-item>
            </t-col>
          </t-row>
        </template>
      </FormInfo>
    </t-form>
  </t-drawer>

  <SelectTable
    v-if="pageData.order.show"
    :loading="pageData.order.loading"
    :showDialog="pageData.order.show"
    title="选择订单"
    width="65vw"
    rowSelectionType="single"
    :tableData="pageData.order.data.records"
    :columns="orderColumns"
    @onConfirm="handleOrderConfirm"
    @onCancel="handleOrderClose"
    :pagination="pageData.order.pagination"
    @page-change="handleOrderPageChange"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.order.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="客户" name="customerMainName">
                <InputSelect :value="pageData.order.filterValue.customerMainName" @onClick="handleCustomerShow" />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="订单" name="orderName">
                <t-input v-model="pageData.order.filterValue.orderName" placeholder="输入订单号搜索..." />
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="订单名称" name="orderName">
                <t-input v-model="pageData.order.filterValue.orderName" placeholder="输入订单名称搜索..." />
              </t-form-item>
            </t-col>
          </t-row>
          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleOrderFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleOrderFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.customer.show"
    :loading="pageData.customer.loading"
    :showDialog="pageData.customer.show"
    title="选择客户"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    :filter-value="pageData.customer.filterValue"
    @filter-change="handleCustomerFilterChange"
    @page-change="handleCustomerPageChange"
    :zIndex="2600"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import { type FormInstanceFunctions } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudTableDataPage, ISelectTableGroups } from "@/types";

// 工具函数
import dayjs from "dayjs";
import { http } from "@/utils/fetch";
import { newPrecision } from "@/utils/tools";

// 常量
import { EDIT_FORM_SAVE_BUTTON, CURRENCY_LIST, PAGINATION_VALUE } from "@/common/constants";

// API
import { getCustomerList } from "@/api/cas";
import { getOrderList } from "@/api/order";

// 业务数据
import { tableColumns as orderColumns } from "@/pages/Dashboard/COM/Order/components/columns";
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";

// import { useUserStore } from "@/stores/modules/user";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    required: true
  }
});

const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/globalExpress/findOne"; // 查询接口
const CREATE_FORM_PATH = "/globalExpress/create"; // 创建接口
const UPDATE_FORM_PATH = "/globalExpress/update"; // 更新接口

const datePickerFormat = "YYYY-MM-DD HH:mm";

const pageData = reactive<Record<string, any>>({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    orderId: "",
    orderName: "",
    contractNo: "",
    startPort: "",
    targetPort: "",
    transferPort: "",
    shipCompany: "",
    billNo: "",
    startExpressTime: new Date().toISOString(),
    cutoffTime: new Date().toISOString(),
    cutoffCustomsTime: new Date().toISOString(),
    arriveTime: new Date().toISOString(),
    typeOfShipping: "",
    shippingCost: 0,
    shippingCostUnit: 0,
    portMiscellaneousFees: 0,
    portMiscellaneousFeesUnit: 0,
    tailDeliveryFees: 0,
    tailDeliveryFeesUnit: 0,
    tax: 0,
    taxUnit: 0
  },
  formRules: {
    orderName: [
      {
        required: true,
        message: "请选择订单",
        type: "error",
        trigger: "blur"
      }
    ],
    startPort: [
      {
        required: true,
        message: "请输入起运港",
        type: "error",
        trigger: "blur"
      }
    ],
    targetPort: [
      {
        required: true,
        message: "请输入目的港",
        type: "error",
        trigger: "blur"
      }
    ],
    shipCompany: [
      {
        required: true,
        message: "请输入船公司",
        type: "error",
        trigger: "blur"
      }
    ],
    billNo: [
      {
        required: true,
        message: "请输入提单号",
        type: "error",
        trigger: "blur"
      }
    ],
    startExpressTime: [
      {
        required: true,
        message: "请输入开船时间",
        type: "error",
        trigger: "blur"
      }
    ],
    cutoffTime: [
      {
        required: true,
        message: "请输入截单时间",
        type: "error",
        trigger: "blur"
      }
    ],
    cutoffCustomsTime: [
      {
        required: true,
        message: "请输入截关时间",
        type: "error",
        trigger: "blur"
      }
    ],
    arriveTime: [
      {
        required: true,
        message: "请输入到港时间",
        type: "error",
        trigger: "blur"
      }
    ],
    typeOfShipping: [
      {
        required: true,
        message: "请输入运输方式",
        type: "error",
        trigger: "blur"
      }
    ],
    transferPort: [
      {
        required: true,
        message: "请输入中转港口",
        type: "error",
        trigger: "blur"
      }
    ],
    shippingCost: [
      {
        required: true,
        message: "请输入海运费",
        type: "error",
        trigger: "blur"
      }
    ],
    portMiscellaneousFees: [
      {
        required: true,
        message: "请输入港杂费",
        type: "error",
        trigger: "blur"
      }
    ],
    tailDeliveryFees: [
      {
        required: true,
        message: "请输入尾端派送费",
        type: "error",
        trigger: "blur"
      }
    ],
    tax: [
      {
        required: true,
        message: "请输入税金",
        type: "error",
        trigger: "blur"
      }
    ]
  },
  customer: {
    show: false,
    loading: false,
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: {}
  } as ISelectTableGroups,
  order: {
    show: false,
    loading: false,
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: { customerMainName: "", customerId: "", status: [], orderNo: "", orderName: "" }
  } as ISelectTableGroups
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;
  }
};

// 获取订单选择列表的方法
const handleOrderShow = () => {
  pageData.order.show = true;
  getOrderData();
};

const getOrderData = async () => {
  pageData.order.loading = true;
  const resultData = await getOrderList(
    pageData.order.pagination.current,
    pageData.order.pagination.pageSize,
    pageData.order.filterValue
  );

  if (resultData.code === 200) {
    pageData.order.data = resultData.data;
    pageData.order.pagination.total = resultData.data.total;
    pageData.order.pagination.current = resultData.data.current;
    pageData.order.pagination.pageSize = resultData.data.size;
    pageData.order.loading = false;
  }
};

const handleOrderPageChange = (pageInfo: Record<string, any>) => {
  pageData.order.pagination.pageSize = pageInfo.pageSize;
  pageData.order.pagination.current = pageInfo.current;
  getOrderData();
};

const handleOrderFilterChange = () => {
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

const handleOrderFilterReset = () => {
  pageData.order.filterValue = { customerMainName: "", customerId: "", status: [], orderNo: "", orderName: "" };
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

const handleOrderConfirm = (e: Record<string, any>) => {
  // console.log(e);
  pageData.formData.orderId = e.options.currentRowData.id;
  pageData.formData.orderName = e.options.currentRowData.orderName;
  pageData.formData.contractId = e.options.currentRowData.contractId;
  pageData.order.show = false;
};

const handleOrderClose = () => {
  pageData.order.show = false;
};

// 获取客户选择列表的方法
const handleCustomerShow = () => {
  pageData.customer.show = true;
  getCustomerData();
};

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.customer.pagination.current,
    pageData.customer.pagination.pageSize,
    pageData.customer.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const handleCustomerConfirm = (e: Record<string, any>) => {
  pageData.order.filterValue.customerId = e.options.currentRowData.id;
  pageData.order.filterValue.customerMainName = e.options.currentRowData.name;
  pageData.customer.show = false;
};

const handleCustomerClose = () => {
  pageData.customer.show = false;
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();

  /* validateResult 在校验没通过的时候返回的是一个 Object，校验通过的时候返回的是
   * 布尔值 true，所以这里写死判断为 true。
   */
  if (validateResult !== true) {
    return;
  }

  let resultData;

  if (props.mode === "view") {
    handleClose();
  }

  const postFormData = structuredClone(toRaw(pageData.formData));

  if (props.mode === "new") {
    // 新增
    resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  } else {
    // 更新
    // postFormData.updatedTime = new Date().toISOString();
    // postFormData.updatedBy = userStore.userData?.id;

    resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
